package com.haohuo.wrapper;

import brave.propagation.CurrentTraceContext;
import brave.propagation.TraceContext;
import com.haohuo.util.TraceIDUtil;
import org.springframework.cloud.sleuth.log.Slf4jCurrentTraceContext;

/**
 * 使用commandrunner时runnable包装
 * 注意：仅在runnner内使用
 *
 * @Author: pk.zhang
 * @Date: 2021/3/17 11:44
 */
public class RunnerRunnable implements Runnable {

    private Runnable runnable;

    private Slf4jCurrentTraceContext  slf4jCurrentTraceContext;

    public RunnerRunnable(Runnable runnable, Slf4jCurrentTraceContext slf4jCurrentTraceContext) {
        this.runnable = runnable;
        this.slf4jCurrentTraceContext = slf4jCurrentTraceContext;
    }

    @Override
    public void run() {
        if (slf4jCurrentTraceContext == null) {
            throw new IllegalArgumentException("slf4jCurrentTraceContext must init!");
        }

        long traceId = TraceIDUtil.incrementAndGet();
        long spanId = TraceIDUtil.incrementAndGet();
        TraceContext build = TraceContext.newBuilder().traceId(traceId)
                .spanId(spanId)
                .parentId(spanId)
                .sampled(Boolean.FALSE)
                .build();
        CurrentTraceContext.Scope scope = slf4jCurrentTraceContext.newScope(build);
        try {
            runnable.run();
        } finally {
            // 执行结束close
            scope.close();
        }
    }
}
